"""add sync module and enhance agent model with acs fields and lifecycle tracking

Revision ID: b49f5453e252
Revises: 841699557267
Create Date: 2025-08-19 23:57:34.284907

"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
import sqlmodel.sql.sqltypes


# revision identifiers, used by Alembic.
revision: str = "b49f5453e252"
down_revision: Union[str, None] = "841699557267"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """Upgrade schema."""
    # ### commands auto generated by Alembic - please adjust! ###

    # 先添加可为NULL的列，然后设置默认值，最后设为NOT NULL
    op.add_column("agent", sa.Column("acs_version", sa.Integer(), nullable=True))
    op.execute("UPDATE agent SET acs_version = 1 WHERE acs_version IS NULL")
    op.alter_column("agent", "acs_version", nullable=False)

    op.add_column("agent", sa.Column("acs_last_seq", sa.BigInteger(), nullable=True))

    # 添加删除相关字段，默认值为False
    op.add_column("agent", sa.Column("is_deleted", sa.Boolean(), nullable=True))
    op.execute("UPDATE agent SET is_deleted = false WHERE is_deleted IS NULL")
    op.alter_column("agent", "is_deleted", nullable=False)

    op.add_column(
        "agent", sa.Column("deleted_at", sa.TIMESTAMP(timezone=True), nullable=True)
    )
    op.add_column(
        "agent",
        sa.Column(
            "deleted_reason",
            sqlmodel.sql.sqltypes.AutoString(length=255),
            nullable=True,
        ),
    )

    # 添加禁用相关字段，默认值为False
    op.add_column("agent", sa.Column("is_disabled", sa.Boolean(), nullable=True))
    op.execute("UPDATE agent SET is_disabled = false WHERE is_disabled IS NULL")
    op.alter_column("agent", "is_disabled", nullable=False)

    op.add_column(
        "agent", sa.Column("disabled_at", sa.TIMESTAMP(timezone=True), nullable=True)
    )
    op.add_column(
        "agent",
        sa.Column(
            "disabled_reason",
            sqlmodel.sql.sqltypes.AutoString(length=255),
            nullable=True,
        ),
    )
    op.create_index(
        op.f("ix_agent_acs_last_seq"), "agent", ["acs_last_seq"], unique=False
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    """Downgrade schema."""
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f("ix_agent_acs_last_seq"), table_name="agent")
    op.drop_column("agent", "disabled_reason")
    op.drop_column("agent", "disabled_at")
    op.drop_column("agent", "is_disabled")
    op.drop_column("agent", "deleted_reason")
    op.drop_column("agent", "deleted_at")
    op.drop_column("agent", "is_deleted")
    op.drop_column("agent", "acs_last_seq")
    op.drop_column("agent", "acs_version")
    # ### end Alembic commands ###
